package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author shkstart
 * @create 2023-04-05 20:05
 */
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    // 发送验证码
    @GetMapping("sendEmail/{email}")
    public Result sendEmail(@PathVariable String email) {
        // 1. 从redis获取验证码，如果获取到直接返回
        String code = (String) redisTemplate.opsForValue().get(email);
        if(!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 2. 如果获取不到，发送邮箱验证码
        String emailCode = RandomUtil.getSixBitRandom();
        boolean isSuccess = msmService.sendEmailCode(email, emailCode);
        // 发送成功
        if (isSuccess) {
            // 设置有效时间
            redisTemplate.opsForValue().set(email, emailCode, 5, TimeUnit.MINUTES);
            return Result.ok();
        }
        return Result.fail().message("发送邮箱验证码失败");
    }
}
